package config

import (
	"encoding/json"
	"flag"
	"github.com/sirupsen/logrus"
	"io/ioutil"
)

//go get gopkg.in/yaml.v2@v2.4.0

import (
	yaml2 "gopkg.in/yaml.v2"
)

var Instance *Config

type Config struct {
	Server struct {
		Port int `yaml:"port"`
	} `yaml:"publisher"`

	// datasource
	Datasource struct {
		DriverName string `yaml:"driverName"`
		Host       string `yaml:"host"`
		Port       int    `yaml:"port"`

		Database string `yaml:"database"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		Charset  string `yaml:"charset"`
	} `yaml:"datasource"`

	Rpcservice struct {
		HostIp     string `yaml:"hostIp"`
		ServerName string `yaml:"serverName"`
		ClientName string `yaml:"clientName"`
	} `yaml:"rpcservice"`
}

func (entity *Config) String() string {
	s, _ := json.Marshal(entity)
	return string(s)

}

func Init(filename string) *Config {
	Instance = &Config{}
	if yamlFile, err := ioutil.ReadFile(filename); err != nil {
		logrus.Error(err)
	} else if err = yaml2.Unmarshal(yamlFile, Instance); err != nil {
		logrus.Error(err)
	}
	return Instance
}

func Ini() *Config {
	var configFile = flag.String("config", "config/application.yml", "配置文件路径")

	flag.Parse() //		fmt.Println(os.Getwd())

	// 初始化配置
	return Init(*configFile)
}
